import { _decorator, Animation, AnimationState, Camera, CapsuleCollider, Component, director, Game, geometry, ICollisionEvent, log, math, Node, PhysicsSystem, RigidBody, v2, v3, Vec3 } from 'cc';
import { EventController, MyEvent } from './EventController';
import { CameraController } from './CameraController';
import { ZTool } from '../ZTool';
import { GameManager } from '../GameManager';
import { AimType, Constant } from '../Constant';
import Banner from '../Banner';
import { AudioManager } from '../AudioManager';
import { EventManager, IncidentEvent } from '../EventManager';
import { NPCController } from './NPCController';
const { ccclass, property } = _decorator;


const v3_1 = v3();
const v3_move = v3();
const ROTATION_STRENGTH = 20.0;//相机旋转速度



@ccclass('PlayerController')
export class PlayerController extends Component {
    @property(Animation)
    animation: Animation = null;//人物动画控制器
    @property()
    jumpVelocity = 1;//跳跃高度
    @property({ type: [Node] })
    carryNode: Node[] = [];//携带物品（0.树枝）

    velocityScale: number = 1.0;//速度倍率
    speeduptime: number = 0;//加速时间
    speedupScale: number = 1;//加速倍率
    speed: number = 1;//速度
    rigidbody: RigidBody = null!;

    camera: Camera = null;
    private cameraController: CameraController = null;



    private _birdNd: Node = null!;
    private _remoteNd: Node = null!;
    private _isInTheAir: boolean = false;//是否在空中
    private InTheAirTime: number = 0;//滞空时间（下坠时间）
    private InTheAirTime2: number = 0;//滞空时间（离开地面时间）
    private _isMoving: boolean = false;
    public _ray: geometry.Ray = null;
    public _PlayerModel: Node = null!;

    protected onLoad(): void {
        this.cameraController = this.node.getChildByPath("CameraPoint/Camera").getComponent(CameraController);
        this.rigidbody = this.node.getComponent(RigidBody);
        this.camera = this.node.getChildByPath("CameraPoint/Camera").getComponent(Camera);
        this._ray = new geometry.Ray();
    }

    start() {
        let collider = this.node.getComponent(CapsuleCollider);
        collider.on('onCollisionEnter', this.onCollisionEnter, this);
        collider.on('onCollisionExit', this.onCollisionExit, this);
        collider.on('onTriggerEnter', this.onTriggerEnter, this);
        collider.on('onTriggerExit', this.onTriggerExit, this);
        this.OnStar();
        EventController.on(MyEvent.JUMP, this.OnJump, this);
        this._PlayerModel = this.node.getChildByPath("PlayerModel/PlayerModel" + GameManager.Instance.PlayerID);
    }

    //启动监听
    OnStar() {
        EventController.on(MyEvent.CAMERA_ROTATE, this.OnRotate, this);
        EventController.on(MyEvent.MOVEMENT, this.OnMove, this);
        EventController.on(MyEvent.MOVEMENT_STOP, this.OnStopMove, this);
    }
    //离开监听
    OnExit() {
        EventController.off(MyEvent.CAMERA_ROTATE, this.OnRotate, this);
        EventController.off(MyEvent.MOVEMENT, this.OnMove, this);
        EventController.off(MyEvent.MOVEMENT_STOP, this.OnStopMove, this);
    }

    private onCollisionEnter(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == AimType.ground) {
            this._isInTheAir = false;
            if (this.InTheAirTime > 1 && GameManager.Instance.PlayerIsOnsteer == false) {
                GameManager.Instance.SetPlayer(2);//玩家摔倒
                GameManager.Instance.inOutdilemma(true, "高空跌落！等待爸爸救援");
            }
            this.InTheAirTime = 0;
            this.InTheAirTime2 = 0;
        }


    }
    private onCollisionExit(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == AimType.ground) {
            this._isInTheAir = true;
        }

    }

    private onTriggerEnter(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == AimType.trap) {
            switch (event.otherCollider.node.name) {
                case "飞天":
                    this.rigidbody.applyForce(v3(0, 10000, 0), v3(0, 100, 0));
                    this.InTheAirTime = 0;
                    break;
                case "秋千碰撞":
                    if (GameManager.Instance.PlayerIsOnsteer == false) {
                        GameManager.Instance.rideid = 0;
                        GameManager.Instance.UICanvas.getChildByName("乘坐").active = true;
                    }
                    break;
                case "板床":
                    this.rigidbody.clearVelocity();
                    this.rigidbody.applyForce(v3(0, 3500, 0), v3(0, 50, 0));
                    EventManager.Emit(IncidentEvent.OverTask, 0);
                    this.InTheAirTime = 0;
                    break;
                case "小车":
                    if (GameManager.Instance.PlayerIsOnsteer == false) {
                        GameManager.Instance.rideid = 1;
                        GameManager.Instance.UICanvas.getChildByName("乘坐").active = true;
                    }
                    break;
                case "小黄鸭":
                    if (GameManager.Instance.PlayerIsOnsteer == false) {
                        GameManager.Instance.rideid = 2;
                        GameManager.Instance.UICanvas.getChildByName("乘坐").active = true;
                    }
                    break;
                case "木马":
                    if (GameManager.Instance.PlayerIsOnsteer == false) {
                        GameManager.Instance.rideid = 3;
                        GameManager.Instance.UICanvas.getChildByName("乘坐").active = true;
                    }
                    break;
                case "洗衣机":
                    console.log("触发洗衣机");

                    break;
                case "马桶":
                    GameManager.Instance.SetPlayer(3);
                    GameManager.Instance.inOutdilemma(true, "真恶心，让爸爸来清理吧！");
                    GameManager.Instance.ChangGeUI(0);
                    EventManager.Emit(IncidentEvent.OverTask, 4);
                    break;
                case "蛋糕":
                    GameManager.Instance.interactionNode = "蛋糕";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "圣诞帽":
                    GameManager.Instance.interactionNode = "圣诞帽";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "狮子头":
                    GameManager.Instance.interactionNode = "狮子头";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "墨水瓶":
                    GameManager.Instance.interactionNode = "墨水瓶";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "马桶搋子":
                    GameManager.Instance.interactionNode = "马桶搋子";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "灭火器":
                    GameManager.Instance.interactionNode = "灭火器";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "辣椒":
                    GameManager.Instance.interactionNode = "辣椒";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "垃圾桶":
                    GameManager.Instance.interactionNode = "垃圾桶";
                    GameManager.Instance.UICanvas.getChildByName("交互").active = true;
                    break;
                case "狗区":
                    GameManager.Instance.PlayerIsOnDogBox = true;
                    break;
                case "楼顶触发":
                    EventManager.Emit(IncidentEvent.OverTask, 10);
                    break;
            }
        }

    }
    private onTriggerExit(event: ICollisionEvent) {
        if (event.otherCollider.getGroup() == AimType.trap) {
            switch (event.otherCollider.node.name) {
                case "秋千碰撞":
                    GameManager.Instance.UICanvas.getChildByName("乘坐").active = false;
                    break;
                case "小车":
                    GameManager.Instance.UICanvas.getChildByName("乘坐").active = false;
                    break;
                case "小黄鸭":
                    GameManager.Instance.UICanvas.getChildByName("乘坐").active = false;
                    break;
                case "木马":
                    GameManager.Instance.UICanvas.getChildByName("乘坐").active = false;
                    break;
                case "狗区":
                    GameManager.Instance.PlayerIsOnDogBox = false;
                    GameManager.Instance.DogNode.getComponent(NPCController).IsOnPathWalkMove = false;
                    break;
                case "蛋糕":
                case "圣诞帽":
                case "狮子头":
                case "墨水瓶":
                case "马桶搋子":
                case "灭火器":
                case "辣椒":
                case "垃圾桶":
                    GameManager.Instance.UICanvas.getChildByName("交互").active = false;
                    break;
            }
        }

    }
    //相机旋转
    OnRotate(deltaX: number, deltaY: number) {
        let eulerAngles = this.cameraController.node.parent.eulerAngles;
        this.cameraController.SetTargetAngle(math.clamp(eulerAngles.x + deltaX * ROTATION_STRENGTH, -30, 30)
            , eulerAngles.y + deltaY * ROTATION_STRENGTH, eulerAngles.z);
    }
    //移动
    OnMove(x: number, y: number, offset: number) {
        this.velocityScale = this.speedupScale;

        let dir = v3(x, 0, -y).normalize();

        let radian = Vec3.angle(Vec3.FORWARD, v3(this.cameraController.node.parent.forward.x, 0, this.cameraController.node.parent.forward.z).normalize());    //Vec3.FORWARD（0，0，-1）

        if (this.cameraController.node.parent.eulerAngles.y < 0) {
            radian = this.cameraController.node.parent.eulerAngles.y % 360 >= -180 ? -radian : radian;
        }

        if (this.cameraController.node.parent.eulerAngles.y > 0) {
            radian = this.cameraController.node.parent.eulerAngles.y % 360 >= 180 ? -radian : radian;
        }

        Vec3.rotateY(v3_move, dir, Vec3.ZERO, radian);


        if (GameManager.Instance.PlayerIsOnsteer) {
            v3_move.multiplyScalar(6);
        } else {
            v3_move.multiplyScalar((this.speed * this.speedupScale));
        }
        this._PlayerModel.parent.forward = v3_move.clone().negative();

        this._isMoving = true;

    }
    //移动停止
    OnStopMove() {
        this._isMoving = false;

        v3_move.set(Vec3.ZERO);
    }
    //跳跃
    OnJump() {
        if (this._isInTheAir) return;
        this.rigidbody.getLinearVelocity(v3_1);
        v3_1.y = this.jumpVelocity;
        this.rigidbody.setLinearVelocity(v3_1);
        this._isInTheAir = true;
    }
    //向上施加推力
    Upforce() {
        this.rigidbody.getLinearVelocity(v3_1);
        v3_1.y = 3;
        this.rigidbody.setLinearVelocity(v3_1);
    }

    private _lastY: number = 0;
    update(deltaTime: number) {
        if (this._isInTheAir && this._lastY > this.node.position.y) {
            this.InTheAirTime += deltaTime;
        }
        if (this._isInTheAir) {
            this.InTheAirTime2 += deltaTime;
        }
        if (this._lastY != this.node.position.y) {
            this._lastY = this.node.position.y;
        } else {
            this._isInTheAir = false;
        }

        //射线检测
        this.camera.screenPointToRay(GameManager.Instance.ScreenCenter.x, GameManager.Instance.ScreenCenter.y, this._ray);
        if (PhysicsSystem.instance.raycastClosest(this._ray, (1 << 0) + (1 << 2), 1000, true)) {
            const result = PhysicsSystem.instance.raycastClosestResult;
            GameManager.Instance.aimType = result.collider.getGroup();
            GameManager.Instance.aimPosition = result.hitPoint;
            switch (result.collider.getGroup()) {

            }
        }
        //移动
        if (this._isMoving) {
            this.rigidbody.getLinearVelocity(v3_1);
            v3_move.y = v3_1.y;
            this.rigidbody.setLinearVelocity(v3_move);
        } else {
            this.rigidbody.getLinearVelocity(v3_move);
            v3_move.set(ZTool.Lerp(v3_move.x, 0, 0.1), v3_move.y, ZTool.Lerp(v3_move.z, 0, 0.1));
            this.rigidbody.setLinearVelocity(v3_move);
        }

        if (this.speeduptime > 0) {
            this.speeduptime -= deltaTime;
            if (this.speeduptime <= 0) {
                this.speedupScale = 1;
                this._PlayerModel.getComponent(Animation).getState("Run").speed = 1.5;
                this.node.getChildByName("拖尾").active = false;
            }
        }
        this.SetAnimation();
    }
    public _Ani: string = "stand";
    //设置动画状态
    SetAnimation() {
        let Ani: string = "stand";
        if (this._isMoving && this.InTheAirTime < 0.04) {
            Ani = "Run";
        } else {
            Ani = "stand";
        }
        if (GameManager.Instance.PlayerIsOnsteer) {
            Ani = "stand";
        }

        if (Ani != this._Ani) {
            this._Ani = Ani;
            this._PlayerModel.getComponent(Animation).play(Ani);
        }

    }

    //添加加速时间
    AddUpSpeedTime(speedScale: number, Time: number) {
        v3_move.multiplyScalar(speedScale);
        this.speedupScale = speedScale;
        this.speeduptime = Time;

        this._PlayerModel.getComponent(Animation).getState("Run").speed = 3;
        this.node.getChildByName("拖尾").active = true;
    }


    onDestroy() {
        EventController.off(MyEvent.MOVEMENT, this.OnMove, this);
        EventController.off(MyEvent.MOVEMENT_STOP, this.OnStopMove, this);
        EventController.off(MyEvent.CAMERA_ROTATE, this.OnRotate, this);
        EventController.off(MyEvent.JUMP, this.OnJump, this);
    }



}


